package org.datavis.renderer;

import java.util.ArrayList;

import org.datavis.chart.Chart;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;

public class ColumnChartRenderer extends ChartRenderer {

	public ColumnChartRenderer(Context context) {
		super(context);
    }
	
	public ColumnChartRenderer(Context context, Chart chart) {
		super(context, chart);
	}
	
	@Override
	public void onDraw(Canvas c) {	
		super.onDraw(c);
		canvas.drawColor(0, android.graphics.PorterDuff.Mode.CLEAR);
		
		mPaint = new Paint(); 
		mPaint.setColor(0xFF000000);  
		mPaint.setStyle(Paint.Style.FILL);
		
		//draw origin
		mPaint.setStrokeWidth(0.3f);
//		DashPathEffect dashPath = new DashPathEffect(new float[]{1,3}, 1);
//		mPaint.setPathEffect(dashPath);		
		canvas.drawLine(0, origin, this.getWidth(), origin, mPaint);
//		mPaint.setPathEffect(null);
		
		//calculate and draw columns
		int barHeight = 0;
		int colorIndex = 0;
		int barIndex = 0;
		int barX = 0;
		int numFields = data.getFields().size();
		intervalSize = calculateWidth(data.getValuesPerEntry(), 1);
		int columnWidth = (int) (intervalSize/(numFields + 1));		
		
		for(ArrayList<Double> values: data.getValues())
		{					
			for (int i = 0; i < values.size(); i++)
			{
				barHeight = 0;
				//calculate barheight from value
				barHeight = calculateHeight(data.getValueRange(), values.get(i));
				
				//calculate bar position
				barX =  columnWidth/2 + intervalSize * i + columnWidth * barIndex;
				
				//set bar color and style
				mPaint.setColor(colors[(colorIndex % colors.length)]); 
				mPaint.setStyle(Paint.Style.FILL);
				
				//draw columns
				if (values.get(i) < 0.)
				{
					canvas.drawRect(barX, origin, columnWidth + barX, (origin + barHeight), mPaint);
					mPaint.setColor(0xff000000);
					mPaint.setStyle(Paint.Style.STROKE);
					canvas.drawRect(barX, origin, columnWidth + barX, (origin + barHeight), mPaint);
				}
				else
				{
					canvas.drawRect(barX, (origin - barHeight), columnWidth + barX, origin, mPaint);
					mPaint.setColor(0xff000000);
					mPaint.setStyle(Paint.Style.STROKE);
					canvas.drawRect(barX, (origin - barHeight), columnWidth + barX, origin, mPaint);
				}
			}
			colorIndex++;	
			barIndex++;
		}
		
		if(chart.getZoomModus() == Chart.ZOOMIN)
			setDrawSelectionRect();	
		
		//draw the bitmap to the real canvas c
		c.drawBitmap(bitmap, 
			new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()), 
			new Rect(0,0,bitmap.getWidth(),bitmap.getHeight()), null);
		
	}
	
	 protected int calculateWidth(double maxValue, double value){
		 	int width = 0;
		 	 
		 	width = (int)(this.getWidth() * (value/maxValue));
		 	
		 	return width;
	}

}
